package com.zhengxyou.jetpackdemo.jobScheduer;

import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.zhengxyou.jetpackdemo.R;

import androidx.appcompat.app.AppCompatActivity;
//https://blog.csdn.net/aroundme/article/details/55214203
//https://www.jianshu.com/p/9fb882cae239
public class JobScheduerActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_job_scheduer);
        findViewById(R.id.btn_job).setOnClickListener(v -> startJob());
    }

    private void startJob() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            JobScheduler jobScheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
            ComponentName componentName = new ComponentName(this, MyJobService.class);
            JobInfo jobInfo = new JobInfo.Builder(1, componentName)
                    .setMinimumLatency(5000)// 任务最少延迟时间
                    .setOverrideDeadline(60000)// 任务deadline，当到期没达到指定条件也会开始执行
                    .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)// 网络条件，默认值NETWORK_TYPE_NONE
                    .setRequiresCharging(true)// 是否充电
                    .setRequiresDeviceIdle(false)// 设备是否空闲
                    .setPersisted(true) //设备重启后是否继续执行
                    .setBackoffCriteria(3000, JobInfo.BACKOFF_POLICY_LINEAR) //设置退避/重试策略
                    .build();
            if (jobScheduler != null) {
                jobScheduler.schedule(jobInfo);
            }
        }
    }

    public static void start(Context context) {
        Intent starter = new Intent(context, JobScheduerActivity.class);
        context.startActivity(starter);
    }
}
